package com.paco.study.cloud.code.controller;

import com.paco.study.cloud.code.feign.EmailFeignClient;
import com.paco.study.cloud.code.feign.UserFeignClient;
import com.paco.study.cloud.code.service.AuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private AuthCodeService authCodeService;

    @Autowired
    private EmailFeignClient emailFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

//    创建验证码
    @GetMapping("/create/{email}")
    public boolean create(@PathVariable String email) {

        Boolean registered = userFeignClient.isRegistered(email);

        if (registered) {
            log.warn("email {} has registered", email);
            return false;
        }

        String code = authCodeService.createCode(email);

        boolean sendStatus = emailFeignClient.send(email, code);

        if (sendStatus) {
            authCodeService.save(email, code);
            return true;
        }
        return false;
    }

//    验证验证码是否正确
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(
            @PathVariable String email,
            @PathVariable String code) {

        return authCodeService.validate(email, code);

    }

}
